package engineer.clientapp.actions;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;





import engineer.clientapp.beans.RegisterUser;
import engineer.clientapp.tools.Connector;
import engineer.clientapp.tools.SendEmail;
import engineer.clientapp.tools.Tool;

public class AddUserAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String target = null;
		ActionErrors actionErrors = new ActionErrors();
		RegisterUser user = (RegisterUser)form;
		String email=user.getEmail();
		String name=user.getName();
		String surname=user.getSurname();
		String address=user.getAddress();
		String pesel=user.getPesel();
		
		String type = "USER";
		FormFile file = user.getFile();
		
		String filePath = "D:/Studia/Projekt Inżynierski/ClientApp/ClientApp/WebContent/images/users";
		File folder = new File(filePath);
		if (!folder.exists()) {
			folder.mkdir();
		}
		
		String fileName = file.getFileName();
		try{
			if(!(name.equals("") || surname.equals("") || address.equals("") || pesel.equals("") || email.equals("") )){
				if(Tool.checkEmailFormat(email)){
					if(Tool.checkPeselFormat(pesel)){
						if (!("").equals(fileName)) {
							File newFile = new File(filePath, fileName);

							if (!newFile.exists()) {
								FileOutputStream fos = new FileOutputStream(newFile);
								fos.write(file.getFileData());
								fos.flush();
								fos.close();
							}
							
							Connection connection = new Connector().getConnection();
				    		Statement statement = connection.createStatement();
				    		String query = "SELECT COUNT(*) FROM automats.users WHERE email='"+email+"'";
					    	ResultSet rs = statement.executeQuery(query);
					    	rs.next();
					    	String password=Tool.setRandomPassword();
					    	
					    	if(rs.getInt("COUNT(*)")==0){
					    		long psl=Long.parseLong(pesel);
				    			statement.executeUpdate("INSERT INTO automats.users (`name`, `surname`, `address`, `pesel`, `email`,`password`, `type`, `foto` ) VALUES(\""+name+"\",\""+surname+"\",\""+address+"\",\""+psl+"\",\""+email+"\",\""+DigestUtils.md5Hex(password)+"\",\""+type+"\",\""+fileName+"\");");
				    			new SendEmail().sendLoginDataEmail(email,password,name,surname, psl, address);
				    			target = "success";
				    			actionErrors.add("error",
										new ActionMessage("error.userCreated"));
				    			rs.close();
								connection.close();
					    	}else{
					    		//uzytkownik juz istnieje
					    		rs.close();
					    		connection.close();
					    		target = "failure";
								actionErrors.add("error",
										new ActionMessage("error.userExist"));
					    	}
					    	
						}else{
							//brak zdjecia
				    		target = "failure";
							actionErrors.add("error",
									new ActionMessage("error.emptyFoto"));
						}
					}else{
						//bledny format pesel
						target = "failure";
						actionErrors.add("error",
								new ActionMessage("error.pesel"));
					}
				}else{
					//bledny format email
					target = "failure";
					actionErrors.add("error",
							new ActionMessage("error.emailFormat"));
				}
			}else{
				target = "failure";
				actionErrors.add("error",
						new ActionMessage("error.emptyFields"));
			}
			
			if (actionErrors.size() != 0) {
				extracted(request, actionErrors);
				return new ActionForward(mapping.getInput());
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return mapping.findForward(target);
	}
	
	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}

}
